const Document = require("../Model/document.model");
const { CreateServiceError } = require("../Constant/err.type");
class DocumentService {
  constructor() {}
  async CreateService(ctx, body) {
    try {
      const { docName, fatherName, fatherId, fileKind, docContain } = body;
      let res = await Document.create({
        docName,
        fatherName,
        fatherId,
        docContain,
        fileKind,
      });
      return res.dataValues;
    } catch (error) {
      CreateServiceError.result = error;
      ctx.app.emit("error", CreateServiceError, ctx);
      return false;
    }
  }
  async UpdateFatherService(id, fatherId) {
    if (fatherId === id) return;
    const res = await Document.findByPk(fatherId);
    const updatedArr = [...res.docContain, id];
    await res.set("docContain", updatedArr);
    await res.save();
  }
  async findSonDocument(id, paranoid) {
    const res = await Document.findByPk(id, {
      paranoid: paranoid,
    });
    console.log(res);
    let SumArr = [];
    if (!res) return SumArr;
    const SonDocArr = [...res.docContain];
    SumArr.push(...SonDocArr);
    if (SonDocArr.length > 0) {
      for (let i = 0; i < SonDocArr.length; i++) {
        SumArr.push(...(await this.findSonDocument(SonDocArr[i], paranoid)));
      }
    } else {
      return [];
    }
    return SumArr;
  }

  async UpdateService() {}
  DeleteService = async (id) => {
    const IDArr = await this.findSonDocument(id, true);
    IDArr.push(id);
    const res = await Document.destroy({ where: { id: IDArr } });
    return res > 0 ? true : false;
  };
  restoreService = async (id) => {
    const IDArr = await this.findSonDocument(id, false);
    IDArr.push(id);
    const res = await Document.restore({ where: { id: IDArr } });
    return res > 0 ? true : false;
  };

  async findService(id) {
    const res = await Document.findByPk(id);
    return res.docContain;
  }
  async reNameService(id, docName) {
    const res = await Document.update(docName, { where: { id } });
    return res > 0 ? true : false;
  }
  getPathService = async (id) => {
    return this.findPath(id);
  };
  async findPath(id) {
    const PathArr = [];
    const { fatherName, fatherId, fileKind } = await Document.findByPk(id);
    PathArr.push({
      fatherName: fatherName,
      fatherId: fatherId,
      fileKind: fileKind,
    });
    if (fatherId != 1) {
      PathArr.push(...(await this.findPath(fatherId)));
    }
    return PathArr;
  }
  async getInfoService(id) {
    const res = await Document.findByPk(id, {
      paranoid: true,
    });
    if (!res) return null;
    return res.dataValues;
  }
}

module.exports = new DocumentService();
